package com.bee.bootstrap.plugs.shiro;

import com.bee.bootstrap.constant.RedisCacheKey;
import com.bee.bootstrap.plugs.redis.RedisCacheManager;
import com.bee.bootstrap.resource.entity.Resource;
import com.bee.bootstrap.roleResource.service.IRoleResourceService;
import com.bee.bootstrap.user.entity.User;
import com.bee.bootstrap.user.service.IUserService;
import com.bee.common.core.result.Result;
import com.bee.common.tools.context.SpringContextUtil;
import com.bee.common.tools.regex.RestfulRegexUtils;
import com.bee.common.tools.web.PermissionConvert;
import net.sf.json.JSONObject;
import org.apache.commons.lang.StringUtils;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authz.AuthorizationException;
import org.apache.shiro.subject.Subject;
import org.apache.shiro.web.filter.AccessControlFilter;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.HttpStatus;
import org.springframework.web.bind.annotation.RequestMethod;

import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.List;

/**
 * 验证资源权限
 * 无须在controller相关的方法上添加shiro的@RequiresPermissions注解
 * 系统根据路径匹配相关资源权限
 */
public class JwtFilter extends AccessControlFilter {

    private Logger LOGGER = LoggerFactory.getLogger(this.getClass());

    @Autowired
    private IRoleResourceService roleResourceServiceImpl;
    private IUserService userServiceImpl;
    private RedisCacheManager redisCacheManager;


    @Override
    protected boolean isAccessAllowed(ServletRequest request, ServletResponse response, Object o) throws Exception{
        HttpServletRequest httpServletRequest = (HttpServletRequest) request;
        String authorization = httpServletRequest.getHeader("Authorization");
        String client=httpServletRequest.getHeader("client");
        JwtToken token = new JwtToken(authorization,client);
        try{
            getSubject(request, response).login(token);
            if(!"APP".equals(client)){
                Subject subject = SecurityUtils.getSubject();
                String uri=((HttpServletRequest)request).getRequestURI();
                String method=((HttpServletRequest) request).getMethod().toLowerCase();
                String resourceCode=uri.split("/",-1)[1];
                String permission=resourceCode+":"+ PermissionConvert.permission(method);
                //从缓存中获取用户能访问的资源
                redisCacheManager= (RedisCacheManager) SpringContextUtil.getBean("redisCacheManager");
                List<Resource> resources= (List<Resource>) redisCacheManager.getCache(RedisCacheKey.RESOURCE_KEY).get(authorization);
                if(resources==null){
                    throw new AuthorizationException();
                }
                boolean access=false;
                //1.先检查URL是否对应
                for(Resource resource:resources){
                    if(RestfulRegexUtils.obverseParametersRegex(uri).equals(RestfulRegexUtils.reverseParametersRegex(resource.getUrl()))){
                        access=true;
                        break;
                    }
                }
                //2.检查含有该资源的*号权限则可以访问所有的
                for(Resource resource:resources){
                    if("*:*".equals(resource.getPermission())||(resource.getPermission().indexOf(resourceCode)>-1&&resource.getPermission().indexOf("*")>-1)){
                        access=true;
                        break;
                    }
                }
                //获取对应uri所需要的permission
                if(StringUtils.isBlank(permission)||!access){
                    LOGGER.error("无权限访问"+((HttpServletRequest)request).getRequestURI());
                    request.setAttribute("msg","无权限访问");
                    return false;
                }else{
                    subject.checkPermission(permission);
                }
            }
            String userToken=new String(org.apache.commons.codec.binary.Base64.decodeBase64(authorization.toString().getBytes()));
            userServiceImpl= (IUserService) SpringContextUtil.getBean("userService");
            User user=userServiceImpl.findUserByToken(userToken);
            request.setAttribute("token",userToken);
            request.setAttribute("userId",user.getId());
        }catch (AuthenticationException e){
            request.setAttribute("msg","token失效");
            LOGGER.error(e.getMessage());
            return false;
        }catch (AuthorizationException e){
            LOGGER.error("无权限访问"+((HttpServletRequest)request).getRequestURI());
            request.setAttribute("msg","无权限访问");
            return false;
        }
        return true;
    }

    @Override
    protected boolean onAccessDenied(ServletRequest request, ServletResponse response) throws Exception {
        response.setContentType("application/json;charset=UTF-8");
        String msg= (String) request.getAttribute("msg");
        response.getWriter().print(JSONObject.fromObject(Result.fail(msg)).toString());
        return false;
    }

    @Override
    protected boolean preHandle(ServletRequest request, ServletResponse response) throws Exception {
        HttpServletRequest httpServletRequest = (HttpServletRequest) request;
        HttpServletResponse httpServletResponse = (HttpServletResponse) response;
        httpServletResponse.setHeader("Access-Control-Allow-Origin", httpServletRequest.getHeader("Origin"));
        httpServletResponse.setHeader("Access-Control-Allow-Credentials", "true");
        httpServletResponse.setHeader("Access-Control-Allow-Methods", "GET,POST,OPTIONS,PUT,DELETE");
        httpServletResponse.setHeader("Access-Control-Allow-Headers", "Content-Type,Authorization,Client");
        httpServletResponse.setHeader("Access-Control-Expose-Headers", "*");
        // 跨域时会首先发送一个option请求，这里我们给option请求直接返回正常状态
        if (httpServletRequest.getMethod().equals(RequestMethod.OPTIONS.name())) {
            httpServletResponse.setStatus(HttpStatus.OK.value());
            return false;
        }
        return super.preHandle(request, response);
    }

}